package com.netsdk.demo.customize;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.structure.DEV_EVENT_TRUCKNOTCLEAN_FOR_PRMA_INFO;
import com.netsdk.lib.structure.NET_TIME_EX;
import com.netsdk.lib.utils.Initialization;
import com.sun.jna.Pointer;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;
import static com.netsdk.lib.NetSDKLib.EVENT_IVS_TRUCKNOTCLEAN_FOR_PRMA;

/**
 * @author 291189
 * @version 1.0
 * @description GIP221208031
 * @date 2022/12/20 14:10
 */
public class TrucknotcleanDemo extends Initialization {

    int channel=-1;
    NetSDKLib.LLong    attachHandle=new NetSDKLib.LLong(0);
    /**
     * 订阅智能任务
     */

    public NetSDKLib.LLong AttachEventRealLoadPic() {
        // 先退订，设备不会对重复订阅作校验，重复订阅后会有重复的事件返回
        if(attachHandle.longValue()!=0){
            this.DetachEventRealLoadPic();
        }

        // 需要图片
        int bNeedPicture = 1;
        attachHandle = netSdk.CLIENT_RealLoadPictureEx(loginHandle, channel, EVENT_IVS_TRUCKNOTCLEAN_FOR_PRMA, bNeedPicture,
                AnalyzerDataCB.getInstance(), null, null);
        if (attachHandle.longValue() != 0) {
            System.out.printf("Chn[%d] CLIENT_RealLoadPictureEx Success\n", channel);
        } else {
            System.out.printf("Chn[%d] CLIENT_RealLoadPictureEx Failed!LastError = %s\n", channel,
                    ToolKits.getErrorCode());
        }

        return attachHandle;
    }
    /**
     * 报警事件（智能）回调
     */
    private static class AnalyzerDataCB implements NetSDKLib.fAnalyzerDataCallBack {
        private final File picturePath;
        private static AnalyzerDataCB instance;

        private AnalyzerDataCB() {
            picturePath = new File("./AnalyzerPicture/");
            if (!picturePath.exists()) {
                picturePath.mkdirs();
            }
        }

        public static AnalyzerDataCB getInstance() {
            if (instance == null) {
                synchronized (AnalyzerDataCB.class) {
                    if (instance == null) {
                        instance = new AnalyzerDataCB();
                    }
                }
            }
            return instance;
        }


        @Override
        public int invoke(NetSDKLib.LLong lAnalyzerHandle, int dwAlarmType, Pointer pAlarmInfo, Pointer pBuffer, int dwBufSize,
                          Pointer dwUser, int nSequence, Pointer reserved) {
            if (lAnalyzerHandle == null || lAnalyzerHandle.longValue() == 0) {
                return -1;
            }

            switch (dwAlarmType) {
                case EVENT_IVS_TRUCKNOTCLEAN_FOR_PRMA : {
                    System.out.println("工程车未清洗");

                    DEV_EVENT_TRUCKNOTCLEAN_FOR_PRMA_INFO msg = new DEV_EVENT_TRUCKNOTCLEAN_FOR_PRMA_INFO();

                    ToolKits.GetPointerData(pAlarmInfo, msg);
                    // 通道号
                    int nChannelID = msg.nChannelID;
                    System.out.println("nChannelID:" + nChannelID);
                    //事件名称
                    byte[] szName = msg.szName;
                    try {
                        System.out.println("szName:" + new String(szName,encode));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    //相对事件时间戳(单位是毫秒)
                    double pts = msg.PTS;
                    System.out.println("pts:" + new Date((long) pts));
                    //UTC时间
                    NET_TIME_EX UTC = msg.UTC;
                    System.out.println("UTC:" + UTC.toStringTime());

                    NetSDKLib.NET_MSG_OBJECT stuObject = msg.stuObject;
                    //物体上相关的带0结束符文本,比如车牌,集装箱号等等
                    byte[] szText
                            = stuObject.szText;
                    byte[] szObjectSubType
                            = stuObject.szObjectSubType;// 物体子类别,根据不同的物体类型,可以取以下子类型：
                    try {
                        System.out.println("szText:"+new String(szText,encode));

                        System.out.println("szObjectSubType:"+new String(szObjectSubType,encode));

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    SavePlatePic(stuObject,pBuffer,dwBufSize);

                    int bSceneImage
                            = msg.bSceneImage;
                    if(bSceneImage==1){
                        NetSDKLib.SCENE_IMAGE_INFO_EX stuSceneImage
                                = msg.stuSceneImage;

                        if ( stuSceneImage.nLength > 0) {
                            String senceExPicture = picturePath + "\\" + System.currentTimeMillis() + "senceEx.jpg";
                            ToolKits.savePicture(pBuffer, stuSceneImage.nOffSet, stuSceneImage.nLength, senceExPicture);
                        }
                    }

                    break;
                }
                default:
                    System.out.println("其他事件--------------------"+ dwAlarmType);
                    break;
            }
            return 0;
        }

        // 2014年后，陆续有设备版本，支持单独传车牌小图，小图附录在pBuffer后面。
        private void SavePlatePic(NetSDKLib.NET_MSG_OBJECT stuObject, Pointer pBuffer, int dwBufSize) {

            // 保存大图
            if (pBuffer != null && dwBufSize > 0) {
            String   bigPicture = picturePath + "\\" + "Big_" + UUID.randomUUID().toString() + ".jpg";
                ToolKits.savePicture(pBuffer, 0, dwBufSize, bigPicture);
            }

            // 保存小图
            if (stuObject == null) {
                return;
            }
            System.out.println("stuObject.bPicEnble:"+stuObject.bPicEnble);
            if (stuObject.bPicEnble == 1) {
                //根据pBuffer中数据偏移保存小图图片文件
                int picLength = stuObject.stPicInfo.dwFileLenth;
                if (picLength > 0) {
                    String    smallPicture = picturePath + "\\" + "small_" + UUID.randomUUID().toString() + ".jpg";
                    ToolKits.savePicture(pBuffer, stuObject.stPicInfo.dwOffSet, picLength, smallPicture);
                }
            }
        }
    }


    /**
     * 停止侦听智能事件
     */
    public void DetachEventRealLoadPic() {
        if (this.attachHandle.longValue() != 0) {
            netSdk.CLIENT_StopLoadPic(this.attachHandle);
        }
    }
    public void RunTest()
    {
        System.out.println("Run Test");
        CaseMenu menu = new CaseMenu();;
        menu.addItem((new CaseMenu.Item(this , "AttachEventRealLoadPic" , "AttachEventRealLoadPic")));
        menu.addItem((new CaseMenu.Item(this , "DetachEventRealLoadPic" , "DetachEventRealLoadPic")));

        menu.run();
    }

    public static void main(String[] args) {
        TrucknotcleanDemo demo=new TrucknotcleanDemo();
        InitTest("172.12.1.54",37777,"admin","admin123");
        demo.RunTest();
        LoginOut();

    }
}
